package com.hina.rec.common.model;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hina.rec.domain.mapper.UserMapper;
import com.hina.rec.domain.model.UserDO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 用户上下文管理类
 * 用于管理用户信息的ThreadLocal存储
 *
 * @author liaosp
 * @date 2025-05-16
 */
@Slf4j
public class UserContext {

    private static final ThreadLocal<UserContextInfo> USER_CONTEXT = new ThreadLocal<>();

    /**
     * 设置当前用户信息
     */
    public static void setUserContext() {
        try {
            if (StpUtil.isLogin()) {
                UserContextInfo userContextInfo = new UserContextInfo();
                userContextInfo.setUserId(StpUtil.getLoginIdAsLong());
                //TODO 日志信息啊,其他信息啊
                USER_CONTEXT.set(userContextInfo);
            }
        } catch (Exception e) {
            log.error("获取用户信息时发生异常", e);
        }
    }

    /**
     * 设置当前用户信息
     */
    public static void setUserContext(Long userId) {
        UserContextInfo userContextInfo = new UserContextInfo();
        userContextInfo.setUserId(userId);
        USER_CONTEXT.set(userContextInfo);
    }

    /**
     * 清除用户信息
     */
    public static void clearUserContext() {
        USER_CONTEXT.remove();
    }

    /**
     * 获取用户名称
     */
    public static String getUserName() {
        UserDO userInfo = getUserInfo();
        return Objects.isNull(userInfo) ? "" : userInfo.getUsername();
    }

    /**
     * 获取当前用户信息
     *
     * @return 用户信息
     */
    public static UserDO getUserInfo() {
        UserContextInfo userContextInfo = USER_CONTEXT.get();
        if (userContextInfo == null || userContextInfo.getUserId() == null) {
            return null;
        }
        UserDO userInfo = userContextInfo.getUserInfo();
        return Objects.isNull(userInfo) ? SpringUtil.getBean(UserMapper.class)
                .selectById(userContextInfo.getUserId()) : userInfo;
    }

    @Data
    public static class UserContextInfo {
        /**
         * 用户信息
         */
        private UserDO userInfo;
        /**
         * 用户ID
         */
        private Long userId;
        /**
         * 请求ID
         */
        private String logId;
    }
}
